package ModelLayer;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import ModelLayer.FileHandlers.SaleFileHandler;

/**
 * This SaleContainer reads sales input. It returns the sale
 * as an object of class Sale.
 * @author frankeskelund, Tobias
 *
 */
public class SaleContainer {
	/**
	 * This is singleton for the SaleContainer
	 */
	private static SaleContainer instance;
	private SaleFileHandler fileHandler;

	private  SaleContainer()
	{
		fileHandler = new SaleFileHandler("Sales");
	}
	
	public static SaleContainer getInstance()
	{
		if(instance == null){
			instance = new SaleContainer();
		}	
		return instance;
	}
	
	/**
	 * Add a sale to a file
	 * @param p insert filled sale object
	 */
	public void addSale(Sale p)
	{
		fileHandler.add(p);
	}
	
	/**
	 * get all sale objects from file
	 * @return Sale objects in ArrayList
	 */
	public ArrayList<Sale> getAllSales()
	{
		// no file, then no Sales
		if (fileHandler == null) {
			return new ArrayList<Sale>();
		}
		
		return fileHandler.getAll();
	}
	
	/**
	 * remove a sale from file by id
	 * @param p insert sale object with id
	 * @return true if a sale was found in file and removed
	 */
	public boolean removeSale(Sale p)
	{
		ArrayList<Sale> Sales = fileHandler.getAll();
		
		Iterator<Sale> iterator = Sales.iterator();
		boolean found = false;
		
		while(iterator.hasNext() && !found)
		{
			Sale nextSale = iterator.next();
			if(nextSale.getId() == p.getId()){
				found = true;
				Sales.remove(nextSale);
			}
		}
		
		if(found){
			fileHandler.update(Sales);
		}
		
		return found;
	}
	
	/**
	 * Finds the matching Sale
	 * @param barcode
	 * @return The found Sale, or null if no matches
	 */
	public Sale findSale(Date date)
	{
		ArrayList<Sale> sales = fileHandler.getAll();
		Iterator<Sale> iterator = sales.iterator();
		
		while(iterator.hasNext())
		{
			Sale nextSale = iterator.next();
			if(nextSale.getProcessingDate().equals(date)){
				return nextSale;
			}
		}
		return null;
	}
}
